package org.zachary.creditbusiness.commodityandhouse.service.impl;

import org.zachary.creditbusiness.commodityandhouse.entity.HouseOrder;
import org.zachary.creditbusiness.commodityandhouse.mapper.HouseOrderMapper;
import org.zachary.creditbusiness.commodityandhouse.service.HouseOrderService;
import org.zachary.creditbusiness.commodityandhouse.util.SendHouseOrder;
import org.zachary.creditbusiness.hotel.util.UUIdUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;

import java.sql.Timestamp;
import java.time.LocalDateTime;

import java.util.List;

@Service
public class HouseOrderServiceImpl implements HouseOrderService {

    @Autowired
    private HouseOrderMapper houseOrderMapper;

    @Autowired
    private SendHouseOrder sendHouseOrder;

    @Override
    public int insert(HouseOrder houseOrder) {
        return houseOrderMapper.insert(houseOrder);
    }

    @Override
    public int update(HouseOrder houseOrder) {
        return houseOrderMapper.updateById(houseOrder);
    }

    @Override
    public int deleteById(Integer id) {
        return houseOrderMapper.deleteById(id);
    }

    @Override
    public HouseOrder selectById(Integer id) {
        return houseOrderMapper.selectById(id);
    }

    @Override
    public List<HouseOrder> selectAll() {
        return houseOrderMapper.selectList(null);
    }

    @Override
    public void placeHouseOrder(HouseOrder houseOrder) {
        // 设置默认值
        houseOrder.setStatus((byte) 0); // 默认状态为未支付
        houseOrder.setPromise((byte) 0); // 默认守约状态
        houseOrder.setPayDate(null); // 支付时间默认为空
        houseOrder.setOverdueMessageSent(false); // 默认未发送逾期消息
        // 生成UUID用于消息队列追踪
        if (houseOrder.getUuid() == null || houseOrder.getUuid().trim().isEmpty()) {
            houseOrder.setUuid(UUIdUtil.createUUId());
        }

        // 插入订单
        houseOrderMapper.insert(houseOrder);
    }

    @Override
    public List<HouseOrder> getOrdersByUserId(Integer userId) {
        QueryWrapper<HouseOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.orderByDesc("start_date"); // 按开始时间降序排列
        return houseOrderMapper.selectList(queryWrapper);
    }


    @Override
    public void payHouseOrder(Integer orderId) {
        // 获取订单信息
        HouseOrder order = houseOrderMapper.selectById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }

        if (order.getStatus() != null && order.getStatus() == 1) {
            throw new RuntimeException("订单已支付");
        }

        Timestamp currentTime = Timestamp.valueOf(LocalDateTime.now());

        // 计算守约状态
        Byte promiseStatus = calculatePromiseStatusOnPayment(order, currentTime);

        System.out.println("支付前订单状态 - 订单ID: " + orderId +
                ", 状态: " + order.getStatus() +
                ", 守约状态: " + order.getPromise() +
                ", 支付时间: " + order.getPayDate() +
                ", 截止时间: " + order.getDeadline());
        System.out.println("计算的新守约状态: " + promiseStatus +
                " (0:守约, 2:固定逾期), 当前时间: " + currentTime);

        // 使用安全的更新方法，只更新指定字段，确保不会影响deadline等其他字段
        int result = houseOrderMapper.updatePaymentStatusOnly(orderId, (byte) 1, currentTime, promiseStatus);
        if (result == 0) {
            throw new RuntimeException("支付失败");
        }

        // 验证deadline字段没有被修改
        HouseOrder updatedOrder = houseOrderMapper.selectById(orderId);
        if (!order.getDeadline().equals(updatedOrder.getDeadline())) {
            System.err.println("警告：支付过程中deadline字段被意外修改！");
            System.err.println("原deadline: " + order.getDeadline());
            System.err.println("新deadline: " + updatedOrder.getDeadline());
            // 如果发现deadline被修改，立即恢复
            UpdateWrapper<HouseOrder> restoreWrapper = new UpdateWrapper<>();
            restoreWrapper.eq("id", orderId).set("deadline", order.getDeadline());
            houseOrderMapper.update(null, restoreWrapper);
        }

        System.out.println("订单支付成功 - 订单ID: " + orderId + ", 守约状态: " + promiseStatus);

        // 重新获取更新后的订单信息，确保有最新的状态
        updatedOrder = houseOrderMapper.selectById(orderId);
        System.out.println("支付后订单状态 - 订单ID: " + orderId +
                ", 状态: " + updatedOrder.getStatus() +
                ", 守约状态: " + updatedOrder.getPromise() +
                ", 支付时间: " + updatedOrder.getPayDate() +
                ", 截止时间: " + updatedOrder.getDeadline());

        // 支付成功后发送消息到消息队列
        try {
            sendHouseOrder.sendMessage(orderId);
            System.out.println("租房订单信用分消息发送成功 - 订单ID: " + orderId);
        } catch (Exception e) {
            System.err.println("租房订单信用分消息发送失败 - 订单ID: " + orderId + ", 错误: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 支付时计算守约状态
     * @param order 订单信息
     * @param payTime 支付时间
     * @return 守约状态 (0: 守约, 2: 固定逾期状态)
     */
    private Byte calculatePromiseStatusOnPayment(HouseOrder order, Timestamp payTime) {
        // 如果在截止日期前支付，显示守约
        if (payTime.before(order.getDeadline()) || payTime.equals(order.getDeadline())) {
            return (byte) 0; // 守约
        }
        // 如果在截止日期后支付，固定为逾期状态
        else {
            return (byte) 2; // 固定逾期状态，不再更新
        }
    }

    @Override
    public int updateOrderStatus(Integer orderId, Integer status, String reason) {
        HouseOrder order = houseOrderMapper.selectById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }

        // 更新订单状态
        order.setStatus(status.byteValue());
        int result = houseOrderMapper.updateById(order);

        System.out.println("订单状态更新成功 - 订单ID: " + orderId + ", 新状态: " + status + ", 原因: " + reason);
        return result;
    }

}
